package com.lmx.project.until;

import java.security.Key;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;
    private static final String CIPHER_TRANSFORM = "AES/ECB/PKCS5Padding";

    // 生成密钥
    public static byte[] generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE);
        Key key = keyGenerator.generateKey();
        return key.getEncoded();
    }

    // 加密
    public static byte[] encrypt(byte[] keyBytes, byte[] plainText) throws Exception {
        Key key = new javax.crypto.spec.SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(plainText);
    }

    // 解密
    public static byte[] decrypt(byte[] keyBytes, byte[] cipherText) throws Exception {
        Key key = new javax.crypto.spec.SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    public static void main(String[] args) {
        try {
            byte[] key = AESUtil.generateKey(); // 生成密钥
            System.out.println("key：" + Arrays.toString(key));
            byte[] plainText = "Hello, World!".getBytes("UTF-8");
            System.out.println("明文：" + new String(plainText, "UTF-8"));

            byte[] cipherText = AESUtil.encrypt(key, plainText); // 加密
            System.out.println("密文：" + Arrays.toString(cipherText));

            byte[] decryptedText = AESUtil.decrypt(key, cipherText); // 解密
            System.out.println("解密后的明文：" + new String(decryptedText, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
